package com.eliza.client.route

import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.util.cio.*
import io.ktor.utils.io.*
import java.io.File

fun Application.configureFile() {
    val uploadsDir = "/home/debi/IdeaProjects/Ktor/client/server/src/main/kotlin/com/eliza/client/route/uploads"
    routing {
        route("/file") {
            post("/upload") {

                val contentLength = call.request.header(HttpHeaders.ContentLength)
                println("contentLength: $contentLength")
                call.receiveMultipart().forEachPart { part ->
                    if (part is PartData.FileItem) {
                        val fileName = "$uploadsDir/${part.originalFileName as String}"
                        println(fileName)
                        val file = File(fileName)
                        part.provider().copyAndClose(file.writeChannel())
                    }
                }
            }
            post("/upload/channel") {
                val file = File("$uploadsDir/ktor_logo.png")
                call.receiveChannel().copyAndClose(file.writeChannel())
                call.respondText("A file is uploaded")
            }
            post("/uploads") {
                var fileDescription = ""
                var fileName = ""

                val multipartData = call.receiveMultipart(formFieldLimit = 1024 * 1024 * 100)
                multipartData.forEachPart { part ->
                    when (part) {
                        is PartData.FormItem -> {
                            fileDescription = part.value
                        }

                        is PartData.FileItem -> {
                            fileName = part.originalFileName as String
                            val file = File("$uploadsDir/$fileName")
                            part.provider().copyAndClose(file.writeChannel())
                        }

                        else -> {}
                    }
                    /*
                    * Resource cleanup
                                Once the form processing is complete, each part is disposed of using the .dispose() function to free resources.
                    * */
                    part.dispose()
                }
                call.respondText("$fileDescription is uploaded to 'uploads/$fileName'")
            }
        }
    }
}
